#include "mainwindow.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QMenu>
#include "dataprovider.h"
#include "passworddialog.h"
#include "printerinfodialog.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setWindowIcon(QIcon(":/icons/icon/logo.jpg"));
    setupUI();
    // applyStyles();
    setupConnections();
}

MainWindow::~MainWindow() {
}

void MainWindow::setupUI(){
    QString title = "好用得效期系统";
    setFixedSize(1000, 680);
    auto dataProvider = DataProvider::instance();
    auto shop = dataProvider->GetShopInfo();
    QString shopName = "";
    if (shop != nullptr) {
        shopName = shop->ShopName;
        title += "-" + shop->ShopName;
    }
    setWindowTitle(title);

    filterEdit = new QLineEdit;
    filterEdit->setPlaceholderText("标签筛选");
    filterEdit->setFixedWidth(200);
    filterEdit->setReadOnly(true);
    QAction *action = new QAction(filterEdit);
    action->setIcon(QIcon(":/icons/icon/close.png"));
    action->setCheckable(true);
    filterEdit->addAction(action, QLineEdit::TrailingPosition);
    filterEdit->setTextMargins(0, 0, 30, 0);
    filterEdit->setStyleSheet("padding:8px;border:1px solid #ddd;border-radius:4px;font: 14px;");
    connect(action, &QAction::triggered, this, [=](bool checked){
        Q_UNUSED(checked);
        filterEdit->clear();
    });


    QHBoxLayout* topLayout = new QHBoxLayout;
    settingButton = new QPushButton();
    settingButton->setIcon(QIcon(":/icons/icon/setting.png"));
    settingButton->setFixedWidth(80);

    QMenu *menu = new QMenu(settingButton);
    printerInfoAction = new QAction(tr("打印机信息"), this);
    batchExpiredAction = new QAction(tr("清空作废标签"), this);
    passwordAction = new QAction(tr("修改密码"), this);
    exitAction = new QAction(tr("退出"), this);
    menu->addAction(printerInfoAction);
    menu->addAction(batchExpiredAction);
    menu->addAction(passwordAction);
    menu->addSeparator();
    menu->addAction(exitAction);
    settingButton->setMenu(menu);

    topLayout->setContentsMargins(0, 0, 10, 0);
    topLayout->addWidget(filterEdit);
    topLayout->addStretch();
    topLayout->addWidget(settingButton);

    keyboard = new VirtualKeyboard;
    keyboard->setFixedHeight(48);
    materialTypeList = new MaterialTypeList;
    materialList = new MaterialList;
    recordList = new RecordList;
    recordDetail = new RecordDetail;


    QWidget* container = new QWidget;
    container->setObjectName("styleContainer");
    container->setContentsMargins(2, 2, 2, 2);
    container->setStyleSheet(
        "QWidget#styleContainer {"  // 精确限定当前容器
        "   background: #f0f0f0;"
        "   border: 2px solid #409EFF;"
        "   border-radius: 5px;"
        "}"
        );
    QHBoxLayout* contentLayout = new QHBoxLayout;
    contentLayout->setContentsMargins(1, 1, 1, 1);
    contentLayout->addWidget(materialTypeList);
    contentLayout->addWidget(materialList);
    contentLayout->addWidget(recordList);
    contentLayout->addWidget(recordDetail);
    container->setLayout(contentLayout);


    QVBoxLayout* mainLayout = new QVBoxLayout;
    mainLayout->addLayout(topLayout, 1);
    mainLayout->addWidget(keyboard, 1);
    QFrame *hline = new QFrame();
    hline->setFrameShape(QFrame::HLine);    // 设置为水平线
    hline->setFrameShadow(QFrame::Sunken);  // 凹陷阴影效果
    // mainLayout->addWidget(hline);
    mainLayout->addWidget(container, 12);
    mainLayout->setAlignment(Qt::AlignHCenter);

    floatButton = new FloatButton();
    // floatButton->setText("效期");
    floatButton->setIcon(QIcon(":/icons/icon/logo.jpg"));
    floatButton->setIconSize(QSize(52, 52));
    floatButton->setGeometry(0, 200, 52, 52);
    floatButton->setVisible(true);
    floatButton->show();

    setCentralWidget(new QWidget);
    centralWidget()->setLayout(mainLayout);
}

void MainWindow::applyStyles() {
    setStyleSheet(R"(
        QDialog { background: #f0f2f5; }
        QLabel { font: 14px; color: #333; }
        QLineEdit {
            padding:8px;
            border:1px solid #ddd;
            border-radius:4px;
            font: 14px;
        }
        QPushButton {
          padding:10px 20px;
          border:2px solid #ddd;
          border-radius:4px;
          font:bold 14px;
        }
        QPushButton[text="登录"] { background:#4890ee; color:white; height: 40px; font: 24px bold;}
        QPushButton[text="登录"]:hover { background:#40a9ff; }
        QPushButton[text="退出"] { background:#ff6666; color:white; height: 40px; font: 24px bold;}
        )"
    );
}

void MainWindow::setupConnections() {
    auto dataProvider = DataProvider::instance();
    connect(printerInfoAction, &QAction::triggered, this, [=]{
        PrinterInfoDialog dialog;
        dialog.exec();
    });

    connect(passwordAction, &QAction::triggered, this, [=]{
        PasswordDialog dialog;
        dialog.exec();
    });

    connect(batchExpiredAction, &QAction::triggered, this, [=]{
        dataProvider->DeleteAllExpiredRecords();
    });

    connect(exitAction, &QAction::triggered, this, [=]{
        close();
    });

    connect(dataProvider, &DataProvider::proccessFailed, this, [=](const QString &error){
        QMessageBox::warning(this, "系统错误", error, QMessageBox::Ok);
    });

    connect(dataProvider, &DataProvider::tokenExpired, this, [=](const QString &error){
        Q_UNUSED(error);
        close();
        QMessageBox::warning(this, "登录过期", "登录已过期，即将退出应用，请重新打开应用。", QMessageBox::Ok);
    });

    connect(floatButton, &QPushButton::clicked, this, [=]{
        if (isVisible()) {
            hide();
        } else {
            show();
        }
    });

    connect(keyboard, &VirtualKeyboard::keyPressed, this, [=](const QString& text){
        QString filterText = filterEdit->text() + text;
        if (filterText.length() > 10) {
            return;
        }
        filterEdit->setText(filterText);
    });

    connect(filterEdit, &QLineEdit::textChanged, this, [=](const QString &text){
        dataProvider->SetShortName(text);
    });
}

void MainWindow::closeEvent(QCloseEvent *event) {
    qDebug() << "closeEvent";
    auto dataProvider = DataProvider::instance();
    if (dataProvider->UploadRecords()) {
        QMessageBox::warning(this, "应用关闭失败", "数据传输中，请稍后再试。", QMessageBox::Ok);
        event->ignore();
        return;
    }

    if (floatButton) {
        floatButton->close();  // 关闭悬浮按钮窗口
        delete floatButton;     // 释放内存
        floatButton = nullptr;
    }
    event->accept();           // 继续关闭主窗口
}
